package com.benshou.bsoa.service.yida;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.aliyun.dingtalkyida_2_0.models.GetFormDataByIDResponse;
import com.aliyun.dingtalkyida_2_0.models.SearchFormDataSecondGenerationResponse;
import com.aliyun.dingtalkyida_2_0.models.SearchFormDataSecondGenerationResponseBody;
import com.benshou.bsoa.constants.SearchConstants;
import com.benshou.bsoa.dto.yida.req.YiDaReq;
import com.benshou.bsoa.dto.yida.req.YiDaSearchReq;
import io.micrometer.common.util.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.benshou.bsoa.constants.ProgressConstants.*;


/*
 * 任务管理的文档汇总
 * 从任务表单获取formInstanceId
 * 将数据更新到文档汇总表单
 */
@Service
public class ProjectProgressService {


    private static final Logger log = LoggerFactory.getLogger(ProjectProgressService.class);

    @Autowired
    private GetYiDaService getYiDaService;

    @Autowired
    private UpdateYiDaService updateYiDaService;

    @Autowired
    private SearchYiDaService searchYiDaService;

    @Value("${dingding.benshou.userId}")
    private String userId;

    @Value("${dingding.benshou.task.formUuid}")
    private String taskFormUuid;

    @Value("${dingding.benshou.document.formUuid}")
    private String documentSummaryFormUuid;

    @Value("${dingding.benshou.project.progress.formUuid}")
    private String projectProgressFormUuid;

    @Value("${dingding.benshou.project.finish.formUuid}")
    private String projectFinishFormUuid;


    /*
     * @param formInstanceId 任务表单实例ID
     * 将任务表单数据更新到文档汇总表单
     */
    public boolean updateProgressDocument(String formInstanceId) throws Exception {
        // 1. 获取项目基本信息
        String projectName = getProjectName(formInstanceId);
        if (StringUtils.isBlank(projectName)) {
            throw new Exception("未能获取有效的项目名称");
        }

        // 2. 查询项目进度下的所有附件
        List<Map<String, Object>> attachments = collectProjectAttachments(projectName);

        // 3. 更新文档汇总表单
        return updateDocumentSummary(projectName, attachments);
    }

    /**
     * 获取项目名称
     * @param formInstanceId 任务表单实例ID
     * @return 项目名称
     * @throws Exception 如果获取失败则抛出异常
     */
    private String getProjectName(String formInstanceId) throws Exception {
        YiDaReq yiDaReq = new YiDaReq(userId, projectFinishFormUuid);
        yiDaReq.setFormInstanceId(formInstanceId);
        GetFormDataByIDResponse response = getYiDaService.querySingleFormData(yiDaReq);

        if (response == null || response.getBody() == null || response.getBody().formData == null) {
            throw new Exception("获取项目信息失败");
        }

        return String.valueOf(response.getBody().formData.get(PROJECT_NAME_OVER));
    }

    /**
     * 收集项目进度表单中的所有附件
     * @param projectName 项目名称
     * @return 附件列表
     * @throws Exception 如果查询失败则抛出异常
     */
    private List<Map<String, Object>> collectProjectAttachments(String projectName) throws Exception {
        // 构建搜索条件
        Map<String, Object> condition = new HashMap<>();
        condition.put(SearchConstants.KEY, PROJECT_NAME_PROGRESS);
        condition.put(SearchConstants.VALUE, projectName);
        condition.put(SearchConstants.TYPE, SearchConstants.TEXT_TYPE);
        condition.put(SearchConstants.OPERATOR, SearchConstants.LIKE_OPERATOR);
        condition.put(SearchConstants.COMPONENT_NAME, SearchConstants.TEXT_FIELD_COMPONENT);
        List<Map<String, Object>> list = Arrays.asList(condition);
        // 执行搜索
        YiDaSearchReq searchReq = new YiDaSearchReq(userId, projectProgressFormUuid);
        searchReq.setSearchCondition(JSON.toJSONString(list));
        SearchFormDataSecondGenerationResponse response = searchYiDaService.searchFormData(searchReq);

        // 检查响应有效性
        if (response == null || response.getBody() == null || response.getBody().getData() == null || response.getBody().getData().isEmpty()) {
            throw new Exception("未找到匹配的项目进度信息");
        }

        // 处理附件数据
        List<Map<String, Object>> fileArrayList = new ArrayList<>();
        Map<String, ?> searchFormData = response.getBody().getData().get(0).formData;
        List<Map<String, ?>> tableData = (List<Map<String, ?>>) searchFormData.get(PROJECT_NAME_PROGRESS_SUB);

        if (tableData != null) {
            for (Map<String, ?> row : tableData) {
                processAttachmentRow(row, fileArrayList);
            }
        }
        return fileArrayList;
    }

    /**
     * 处理每一行的附件数据
     * @param row 当前行数据
     * @param fileArrayList 附件列表
     */
    private void processAttachmentRow(Map<String, ?> row, List<Map<String, Object>> fileArrayList) {
        Object attachmentField = row.get(ATTACHMENT_NAME);
        if (!(attachmentField instanceof String) || StringUtils.isBlank((String) attachmentField)) {
            return;
        }

        try {
            List<Map<String, Object>> attachmentList = JSON.parseObject(
                    (String) attachmentField,
                    new TypeReference<List<Map<String, Object>>>() {});

            if (attachmentList != null) {
                for (Map<String, ?> attachment : attachmentList) {
                    Map<String, Object> fileMap = new HashMap<>();
                    fileMap.put(DOWNLOAD_URL, String.valueOf(attachment.get("downloadUrl")));
                    fileMap.put(NAME, String.valueOf(attachment.get("name")));
                    fileArrayList.add(fileMap);
                }
            }
        } catch (Exception e) {
            // 记录日志但继续处理其他附件
            log.error("解析附件数据失败", e);
        }
    }

    /**
     * 更新文档汇总表单
     * @param projectName 项目名称
     * @param attachments 附件列表
     * @return 是否更新成功
     * @throws Exception 如果更新失败则抛出异常
     */
    private boolean updateDocumentSummary(String projectName, List<Map<String, Object>> attachments) throws Exception {
        // 构建搜索条件
        Map<String, Object> condition = new HashMap<>();
        condition.put(SearchConstants.KEY, PROJECT_NAME_DOCUMENT);
        condition.put(SearchConstants.VALUE, projectName);
        condition.put(SearchConstants.TYPE, SearchConstants.TEXT_TYPE);
        condition.put(SearchConstants.OPERATOR, SearchConstants.LIKE_OPERATOR);
        condition.put(SearchConstants.COMPONENT_NAME, SearchConstants.TEXT_FIELD_COMPONENT);
        // 将条件封装为列表
        List<Map<String, Object>> list = Arrays.asList(condition);
        // 搜索文档汇总表单
        YiDaSearchReq searchReq = new YiDaSearchReq(userId, documentSummaryFormUuid);
        searchReq.setSearchCondition(JSON.toJSONString(list));
        SearchFormDataSecondGenerationResponse response = searchYiDaService.searchFormData(searchReq);

        // 检查响应有效性
        if (response == null || response.getBody() == null || response.getBody().getData() == null || response.getBody().getData().isEmpty()) {
            throw new Exception("未找到匹配的文档汇总信息");
        }

        // 准备更新数据
        String summaryFormInstanceId = response.getBody().getData().get(0).getFormInstanceId();
        Map<String, Object> formDataMap = new HashMap<>();
        formDataMap.put("attachmentField_mbk86oko", attachments);

        // 执行更新
        YiDaReq updateReq = new YiDaReq(userId, documentSummaryFormUuid);
        updateReq.setFormInstanceId(summaryFormInstanceId);
        updateReq.setFormDataJson(JSON.toJSONString(formDataMap));

        return updateYiDaService.updateFormData(updateReq) != null;
    }
}
